package com.service.infoEntry.controller;

import com.service.config.utils.JsonXMLUtils;
import com.service.config.utils.RedisUtil;
import com.service.config.utils.Result;
import com.service.config.utils.UserTokenManager;
import com.service.infoEntry.dto.TransactionInfoDto;
import com.service.infoEntry.dto.UserDto;
import com.service.infoEntry.entity.ContentOfUpdateInfo;
import com.service.infoEntry.entity.ProgrammeInfo;
import com.service.infoEntry.service.TransactionService;
import com.service.infoEntry.vo.TransactionVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.util.List;
import java.util.Map;

import static com.service.infoEntry.constant.Constant.*;

/**
 * 事务controller
 * @author hjl
 */
@CrossOrigin
@RestController()
@RequestMapping("/transaction")
@Api(value = "事务相关接口")
public class TransactionController {
    @Resource
    RedisUtil redisUtil;
    @Resource
    TransactionService transactionService;

    @ApiOperation(value = "记录事务")
    @RequestMapping(value ="/saveTransaction",method = RequestMethod.POST)
    @ResponseBody
    public Result saveTransaction(@RequestBody TransactionInfoDto transactionInfoDto,
                              @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);

                transactionInfoDto.setUserId(userId);
                return transactionService.addTransaction(transactionInfoDto,userDto);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "事务跟踪")
    @RequestMapping(value ="/updateTransaction",method = RequestMethod.POST)
    @ResponseBody
    public Result updateTransaction(@RequestBody TransactionInfoDto transactionInfoDto,
                                @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);

                return transactionService.updateTransaction(transactionInfoDto,userDto);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "事务关闭")
    @RequestMapping(value ="/closeTransaction",method = RequestMethod.POST)
    @ResponseBody
    public Result closeTransaction(@RequestBody TransactionInfoDto transactionInfoDto,
                               @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);

                transactionService.closeTransaction(transactionInfoDto);
                return Result.ok();
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 基于单号的精确搜索
     * @param no 订单号
     * @param cloudAuthToken
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "基于单号精确搜索")
    @RequestMapping(value ="/searchTransactionByNo",method = RequestMethod.GET)
    public Result searchTransactionByNo(@RequestParam("no")String no,
                                        @RequestParam("teamId")@ApiParam("teamId") String teamId,
                                    @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);

                TransactionVo transactionVo = transactionService.searchTransactionByNo(no,userId,teamId);
                return Result.ok().setData(transactionVo);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "查询事务")
    @RequestMapping(value = "/queryTransaction",method = RequestMethod.GET)
    @ResponseBody
    public Result queryTransaction(@RequestParam("teamId") String teamId,
                                           @RequestParam(value = "status",required = false) Integer status,
                                           @RequestParam(value = "desc",required = false) String desc,
                                           @RequestParam(value = "transactionStatus",required = false) Integer transactionStatus,
                                           @RequestParam(value = "page",required = true) Integer page,
                                           @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                Map<String,Object> map= transactionService.searchTransaction(teamId,userId,desc,status,transactionStatus,page);
                return Result.ok().setData(map);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "导出事务清单")
    @RequestMapping(value ="/exportTransactionList",method = RequestMethod.GET)
    @ResponseBody
    public Result exportTransactionList(@RequestParam("teamId") String teamId,
            @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                String filePath = transactionService.exportTransactionList(teamId,userId);
                return Result.ok().setData(filePath);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 项目清单上传
     * @param file
     * @return ok
     * @throws Exception
     */
    @ApiOperation(value = "事务清单上传")
    @RequestMapping(value = "uploadTransactionList", method = RequestMethod.POST)
    @ResponseBody
    public Result uploadProgrammeList(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                      @RequestParam("file")  @ApiParam("文件") MultipartFile file,
                                      @RequestParam("teamId") String teamId) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                return  transactionService.uploadTransactionList(file,teamId,userDto);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 下拉框查询所有项目名称
     * @param cloudAuthToken
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "下拉框查询所有项目名称")
    @RequestMapping(value ="/getProgrammeName",method = RequestMethod.GET)
    public Result getProgrammeName(@RequestParam("teamId") String teamId,
                                   @RequestParam("type")@ApiParam("type=1查询正常项目数据;type=0查询已删除和正常项目数据") int type,
                                        @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                List<ProgrammeInfo> programmeInfos = transactionService.getProgrammeName(teamId,userId,type);
                return Result.ok().setData(programmeInfos);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 查询事务更新进展记录
     * @param cloudAuthToken
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "查询事务更新进展记录")
    @RequestMapping(value ="/queryUpdateProcessOfTransaction",method = RequestMethod.GET)
    public Result queryUpdateProcess(@RequestParam(value = "teamId",required = false) String teamId,
                                     @RequestParam(value = "transactionNO",required = false) String transactionNO,
                                   @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                List<ContentOfUpdateInfo> updateProcess = transactionService.queryUpdateProcess(teamId,userId,transactionNO);
                return Result.ok().setData(updateProcess);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
}
